package com.wgchao;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: JwtUtil
 * @author: wgchao
 * @createTime: 2021/11/19 10:10 AM
 * @Description: token工具
 */
public class JwtUtil {

    private static final String signKey = "%*&)*^!(";

    //过期时间 1天
    private static final long ttl = 1000*60*60*24;

    private static JWTSigner getJWTSigner(){
        return JWTSignerUtil.hs256(signKey.getBytes());
    }

    /**
     * 创建JWT
     * @param uname 账户名 写入token并用于jwt签名
     * @param organ 机构编号
     * @param type 类型 local/service/external
     * @return token
     */
    public static String createJWT(String uname, String organ, String type){
        Map<String, Object> map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;
            {
                put("uname", uname);
                put("organ", organ);
                put("type", type);
                put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
            }
        };
        return JWTUtil.createToken(map, getJWTSigner());
    }

    /**
     * 验证并解析token 验证失败，抛出异常
     * @param token
     * @return JWT
     * @exception
     */
    public static JWT validAndParseToken(String token) {
        try{
            JWTSigner jwtSigner = getJWTSigner();
            // 验证算法
            JWTValidator jwtValidator = JWTValidator.of(token).validateAlgorithm(jwtSigner);
            if(JWTUtil.verify(token, jwtSigner)){
                jwtValidator.validateDate();
                return JWTUtil.parseToken(token);
            }else{
                throw new RuntimeException("token不正确");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("");
        }
    }

    /**
     * 获取jwt中附带信息
     * @param jwt
     * @param key 键值
     * @return
     */
    public static Object getPayload(JWT jwt, String key){
        return jwt.getPayload(key);
    }

}
